import { Component } from 'react'
import { Card, Form, Input, Checkbox, Button, message } from 'antd'
import logo from '../../assets/logo.png'
import './index.css'
import { login } from '../../api/user'
import { setToken } from '../../utils/storage'
export default class Login extends Component {
    onFinish = async (values) => {
        const { mobile, code } = values
        try {
            const res = await login(mobile, code)
            // 存储token
            // localStorage.setItem('geek_pc', res.data.token)
            setToken(res.data.token)

            // 跳转到首页
            const { state } = this.props.location

            if (state) {

                this.props.history.push(state.from.pathname)
            } else {
                this.props.history.push('/home')
            }
            message.success('登录成功')
        } catch (err) {
            message.error(err.response.data.message, 1)
        }
    }
    render() {
        return (
            <div className="login">
                <Card className="login-container">
                    <img className="login-logo" src={logo} alt="" />
                    {/* 表单 */}
                    <Form size="large" validateTrigger={['onChange', 'onBlur']} onFinish={this.onFinish} initialValues={{
                        agree: true,
                        mobile: '13911111111',
                        code: '246810',
                    }}>
                        <Form.Item name="mobile"
                            // 自定义校验
                            rules={[
                                { required: true, message: '手机号码不能为空' },
                                { pattern: /^1[3-9]\d{9}$/, message: '手机号码格式错误' },
                            ]}>
                            <Input placeholder="请输入手机号" />
                        </Form.Item>
                        <Form.Item name="code" rules={[
                            { required: true, message: '验证码不能为空' },
                            { pattern: /^\d{6}$/, message: '验证码格式错误' },
                        ]}>
                            <Input placeholder="请输入验证码" />
                        </Form.Item>
                        <Form.Item name="agree" valuePropName="checked" rules={[
                            {
                                validator: (_, value) =>
                                    value === true ? Promise.resolve() : Promise.reject('请阅读并同意用户协议'),
                            },
                        ]}>
                            <Checkbox>我已阅读并同意[用户协议]和[隐私条款]</Checkbox>
                        </Form.Item>
                        <Form.Item>
                            <Button type="primary" htmlType="submit" block>
                                登录
                            </Button>
                        </Form.Item>
                    </Form>
                </Card>
            </div>
        )
    }
}